import React, {useState} from 'react';
import {Button, List, message, Modal, Tooltip, Upload} from 'antd';
import {DeleteOutlined, FileOutlined, UploadOutlined} from '@ant-design/icons';
import {UploadFile} from 'antd/es/upload/interface';
import {parseFiles} from '../api/uploadController';
import {useTheme} from '../context/ThemeContext';

interface FileUploadProps {
    onFilesParsed?: (fileIds: string[]) => void;
}

const FileUpload: React.FC<FileUploadProps> = ({onFilesParsed}) => {
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [uploading, setUploading] = useState(false);
    const [showFiles, setShowFiles] = useState(false);

    const {theme: currentTheme} = useTheme();
    const isInk = currentTheme === 'ink';

    const handleUpload = async () => {
        const formData = new FormData();
        fileList.forEach((file) => {
            formData.append('files', file as any);
        });

        setUploading(true);

        try {
            // 调用上传API
            const response = await parseFiles({files: fileList.map(file => file.name)}, {
                data: formData,
            });

            // 根据API响应的数据结构来访问结果
            const result = response.data;

            if (result && result.code === 0 && result.data) {
                message.success('文件上传成功');
                // 假设API返回的是文件ID的数组
                if (onFilesParsed) {
                    // 确保我们传递的是字符串数组
                    onFilesParsed([result.data]);
                }
                setFileList([]);
            } else {
                message.error('文件上传失败');
            }
        } catch (error) {
            console.error('上传错误:', error);
            message.error('文件上传出错');
        } finally {
            setUploading(false);
        }
    };

    const props = {
        onRemove: (file: UploadFile) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
        },
        beforeUpload: (file: UploadFile) => {
            setFileList([...fileList, file]);
            return false;
        },
        fileList,
    };

    return (
        <div style={{
            position: 'fixed',
            bottom: '20px',
            right: '20px',
            zIndex: 1000,
        }}>
            <Tooltip title="上传文件">
                <Button
                    type="primary"
                    shape="circle"
                    size="large"
                    icon={<UploadOutlined/>}
                    onClick={() => setShowFiles(true)}
                    style={{
                        background: isInk ? 'var(--gradient)' : 'var(--gradient)',
                        boxShadow: 'var(--shadow)',
                    }}
                />
            </Tooltip>

            <Modal
                title={
                    <div style={{
                        fontFamily: 'var(--font-family)',
                        fontSize: '18px',
                        color: 'var(--text-color)',
                        borderBottom: `2px solid var(--primary-color)`,
                        paddingBottom: '8px'
                    }}>
                        文件上传
                    </div>
                }
                open={showFiles}
                onCancel={() => setShowFiles(false)}
                footer={[
                    <Button key="back" onClick={() => setShowFiles(false)}>
                        取消
                    </Button>,
                    <Button
                        key="submit"
                        type="primary"
                        loading={uploading}
                        onClick={handleUpload}
                        disabled={fileList.length === 0}
                        style={{
                            background: 'var(--gradient)',
                        }}
                    >
                        {uploading ? '上传中' : '开始上传'}
                    </Button>,
                ]}
                bodyStyle={{
                    fontFamily: 'var(--font-family)',
                }}
            >
                <Upload {...props}>
                    <Button icon={<UploadOutlined/>}>选择文件</Button>
                </Upload>

                {fileList.length > 0 && (
                    <List
                        style={{marginTop: '20px'}}
                        header={<div>已选择的文件</div>}
                        bordered
                        dataSource={fileList}
                        renderItem={(item) => (
                            <List.Item
                                actions={[
                                    <Button
                                        type="text"
                                        danger
                                        icon={<DeleteOutlined/>}
                                        onClick={() => props.onRemove(item)}
                                    />
                                ]}
                            >
                                <List.Item.Meta
                                    avatar={<FileOutlined/>}
                                    title={item.name}
                                    description={`${(item.size! / 1024).toFixed(2)} KB`}
                                />
                            </List.Item>
                        )}
                    />
                )}
            </Modal>
        </div>
    );
};

export default FileUpload; 